package com.goldenautumn.prefabricate.activity.splash

import com.blankj.utilcode.util.SPUtils
import com.goldenautumn.prefabricate.MainActivity
import com.goldenautumn.prefabricate.R
import com.goldenautumn.prefabricate.activity.account.LoginActivity
import com.goldenautumn.prefabricate.activity.account.PhoneLoginActivity
import com.goldenautumn.prefabricate.databinding.ActivitySplashBinding
import com.goldenautumn.prefabricate.utils.Constants.IS_FIRST_INSTALL
import com.goldenautumn.prefabricate.utils.goToStartActivity
import com.tencent.bugly.crashreport.CrashReport
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.isActive
import kotlinx.coroutines.selects.select
import qncx.external.common.base.BaseActivity
import qncx.external.common.room.RoomSql
import qncx.external.common.utils.intent
import qncx.external.common.utils.ticker
import qncx.external.common.widget.dialog.PrivacyDialog
import java.util.concurrent.TimeUnit

class SplashActivity : BaseActivity<ActivitySplashBinding>() {

    var time = 3

    var isTime = false

    override fun getLayoutId(): Int = R.layout.activity_splash

    override suspend fun main() {
        RoomSql.init(this)
        mBinding.tick.text = String.format(getString(R.string.sp_skip),"3")

        var isFirst = SPUtils.getInstance().getBoolean(IS_FIRST_INSTALL, true)

        if (!isFirst) afterAgree()
        else PrivacyDialog(resources.getStringArray(R.array.user_agreement)) {
            SPUtils.getInstance().put(IS_FIRST_INSTALL, false)
            afterAgree()
        }.onShow(supportFragmentManager.beginTransaction())

        mBinding.tick.setOnClickListener { time = 1 }

        var ticker = ticker(TimeUnit.SECONDS.toMillis(1))

        while (isActive) {
            select<Unit> {
                events.onReceive {
                    when (it) {
                        Event.StartActivity -> {
                            goToStartActivity(intent, this@SplashActivity)
                        }

                        else -> Unit
                    }
                }
                ticker.onReceive {
                    if (isTime) {
                        if (time != 1) {
                            time -= 1
                            mBinding.tick.text = String.format(getString(R.string.sp_skip),"$time")
                        } else onSkip(ticker)
                    }
                }

            }
        }
    }

    fun afterAgree() {
        //初始化各种SDK
        isTime = true
        CrashReport.initCrashReport(applicationContext, "aaf8bee930", false)
    }

    fun onSkip(ticker: Channel<Long>?) {
        ticker?.cancel()
        startActivity(MainActivity::class.intent)
        overridePendingTransition(0, 0)
        finish()
    }

}
